import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import Input from '../components/common/Input';
import Button from '../components/common/Button';
import { login } from '../utils/auth';
import styles from './Login.module.css';
const Login = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const history = useHistory();

    const handleSubmit = async (e) => {
        console.log('handleSubmit called');
        e.preventDefault();
        try {
            await login(username, password);
            // history.push('/dashboard');
            alert('登录成功！');
        } catch (err) {
            setError('登录失败，请检查您的凭据。');
        }
    };

    return (
        <div className={styles.loginBox}>
            <h2>登录</h2>
            {error && <p>{error}</p>}
            <form className={styles.loginForm} onSubmit={handleSubmit}>
                <Input 
                    type="text" 
                    placeholder="用户名" 
                    value={username} 
                    onChange={(e) => setUsername(e.target.value)} 
                />
                <Input 
                    type="password" 
                    placeholder="密码" 
                    value={password} 
                    onChange={(e) => setPassword(e.target.value)} 
                />
                <Button type="submit" btnTxt="登录" ></Button>
            </form>
        </div>
    );
};

export default Login;